import frida
import sys
import time

def on_message(message, data):
    print(f"[Frida Message] {message}")

def get_app_pid(device, bundle_id, max_retries=10, delay=1):
    """等待并获取应用的PID"""
    for _ in range(max_retries):
        try:
            apps = device.enumerate_applications()
            for app in apps:
                if app.identifier == bundle_id:
                    if app.pid != 0:
                        return app.pid
            print(f"Waiting for {bundle_id} to start...")
            time.sleep(delay)
        except Exception as e:
            print(f"Error enumerating apps: {e}")
            time.sleep(delay)
    raise RuntimeError(f"Failed to find running {bundle_id} after {max_retries} retries")

def main():
    bundle_id = "com.gzlk.mfadtw"  # 替换为你的应用Bundle ID
    js_file = "main.js"  # 确保此文件与脚本在同一目录

    try:
        # 获取USB设备
        device = frida.get_usb_device()

        print(f"Waiting for {bundle_id} to start...")
        pid = get_app_pid(device, bundle_id)

        print(f"Attaching to PID: {pid}")
        session = device.attach(pid)

        # 读取并加载JS脚本
        with open(js_file, "r", encoding="utf-8") as f:
            js_code = f.read()

        script = session.create_script(js_code)
        script.on("message", on_message)
        script.load()

        print(f"Successfully injected into {bundle_id} (PID: {pid})")
        print("Press Ctrl+C to stop...")
        sys.stdin.read()

    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    main()